use std::path::Path;

use directories::BaseDirs;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};

// 创建一个全局的DB_POOL，可以一直使用，启动的时候初始化即可
static DB_POOL: OnceCell<Pool<Sqlite>> = OnceCell::new();

// 初始化数据库链接池

pub async fn init_mysql_pool(db_url: &str, mut path: String) {
    println!("初始化数据库线程池--------开始-------");

    if path.is_empty() {
        if let Some(base_dirs) = BaseDirs::new() {
            let appdata_dir = base_dirs.data_dir();
            path += appdata_dir.to_str().unwrap();
            println!("AppData directory: {:?}", appdata_dir);
        }
    }
    // let mut path = String::from("");
    // if let Some(base_dirs) = BaseDirs::new() {
    //     let appdata_dir = base_dirs.data_dir();
    //     path += appdata_dir.to_str().unwrap();
    //     println!("AppData directory: {:?}", appdata_dir);
    // }
    //path += "\\com.salary_calculator.app";
    let path = Path::new(&path);

    let dir = path.display().to_string();
    //let path = "C:\\Users\\tjw1t\\AppData\\Roaming\\tk.tools";

    if let Ok(metadata) = std::fs::metadata(path.join(db_url)) {
        if !metadata.is_file() {
            std::fs::create_dir_all(dir.clone());
            std::fs::File::create(path.join(db_url));
        }
    } else {
        std::fs::create_dir_all(dir.clone());
        std::fs::File::create(path.join(db_url));
    }
    log::info!(
        "链接数据库！{}",
        &("sqlite:".to_string() + &path.join(db_url).display().to_string())
    );
    let pool = SqlitePoolOptions::new()
        .connect_lazy(&("sqlite:".to_string() + &path.join(db_url).display().to_string()))
        .ok()
        .expect("链接失败");
    log::info!("开始执行语句");
    // 执行一个 SQL 查询，例如创建一个表
    let _ = sqlx::query(
        "


CREATE TABLE 'ageing' (
  'id' text NOT NULL,
  'date' text NOT NULL,
  'work_time' real DEFAULT 0,
  'work_num' real DEFAULT 0,
  'create_time' integer,
  'creator_lid' TEXT,
  'creator_name' TEXT,
  'updater_lid' TEXT,
  'updater_name' TEXT,
  'up_ver' integer,
  'sort' integer,
  'tenant_id' TEXT,
  'deleted' TEXT,
  'update_time' integer,
  PRIMARY KEY ('id')
);


      ",
    )
    .execute(&pool)
    .await;
    log::info!("执行语句完成！");
    DB_POOL
        .set(pool)
        .unwrap_or_else(|_| println!("try insert pool cell failure!"));
    // DB_POOL.set(mysql::Pool::new(db_url).expect(&format!("Error connecting to {}", &db_url)))
    //     .unwrap_or_else(|_| { info!("try insert pool cell failure!") });
    println!("初始化数据库线程池--------结束-------");
}

// 从链接链接池里面获取链接
pub fn get_connect() -> Pool<Sqlite> {
    //println!("从链接池获取数据库链接----------开始----------");
    let conn = DB_POOL.get().expect("Error get pool from OneCell<Pool>").clone();
    //println!("从链接池获取数据库链接----------结束----------");
    conn
}

#[derive(Serialize, Deserialize)]
pub struct Timer {
    time: String,
    id: i64,
}
